import { REG } from "@/data/locations";
import { GetAsyncDomUtil } from "./coreUtils";

export const datasetCore: {
  status:
    | "init"
    | "coreLoad"
    | "modulesLoad"
    | "hotFixes"
    | "extra"
    | "load"
    | string;
} = {
  status: "",
};

export const headReady = (callback: () => any): Promise<() => any> => {
  return new Promise((resolv, reject) => {
    if (document.head) {
      resolv(callback());
    } else {
      GetAsyncDomUtil.getAsyncDom("head", () => {
        resolv(callback());
      });
    }
  });
};

export const playerReady = (callback: () => any) => {
  if (!REG.videoAndBangumi.test(location.href)) {
    return;
  }
  return new Promise((resolv, reject) => {
    if (document.querySelector(".quality-panel")) {
      resolv(callback());
    } else {
      GetAsyncDomUtil.getAsyncDom(".quality-panel", () => {
        resolv(callback());
      });
    }
  });
};

export const footerReady = (callback: () => any): Promise<any> => {
  return new Promise((resolv, reject) => {
    if (document.querySelector("#footer")) {
      resolv(callback());
    } else {
      GetAsyncDomUtil.getAsyncDom("#footer", () => {
        resolv(callback());
      });
    }
  });
};

export const loaded = (callback: () => void) => {
  return new Promise((resolv, reject) => {
    if (document.readyState == "complete") {
      resolv(callback());
    } else {
      globalThis.addEventListener("load", () => {
        resolv(callback());
      });
    }
  });
};

export const commentAreaReady = (callback: () => any) => {
  return new Promise((resolv, reject) => {
    const nodes = document.querySelector(".ac-comment-root-list");
    const loading = document.querySelector(".ac-comment-loading")?.innerHTML;
    if (nodes && loading == "") {
      resolv(callback());
    } else {
      GetAsyncDomUtil.getAsyncDom(".ac-comment-root-list", () => {
        resolv(callback());
      });
    }
  });
};

export async function modLoadTrace(modLoadCall: () => any): Promise<number> {
  const startTime = performance.now();
  modLoadCall();
  const endTime = performance.now();
  return endTime - startTime;
}
